import {
  VuexModule,
  Module,
  Mutation,
  Action,
  getModule
} from 'vuex-module-decorators'
import { RouteConfig } from 'vue-router'
import { constantRoutes } from '@/router'
import Layout from '@/layout/index.vue'

import store from '@/store'

const hasPermission = (roles: string[], route: RouteConfig) => {
  if (route.meta && route.meta.roles) {
    return roles.some(role => (route as any).meta.roles.includes(role))
  } else {
    return true
  }
}

export const filterAsyncRoutes = (routes: RouteConfig[], roles: string[]) => {
  const res: RouteConfig[] = []
  routes.forEach(route => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

export interface IPermissionState {
  routes: RouteConfig[]
  dynamicRoutes: RouteConfig[]
}

@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
  public routes: RouteConfig[] = []
  public dynamicRoutes: RouteConfig[] = []

  @Mutation
  private SET_ROUTES(routes: RouteConfig[]) {
    this.routes = constantRoutes.concat(routes)
    this.dynamicRoutes = routes
  }

  @Mutation
  public INIT_LOCAL_ROUTES() {
    this.routes = constantRoutes
  }

  @Mutation
  public CLEAN_ROUTES() {
    this.routes = []
    this.dynamicRoutes = []
  }

  @Action
  public GenerateRoutes(menu: any[]) {
    console.log(menu)
    const accessedRoutes: any[] = []
    menu.forEach((menu: any) => {
      const route = {
        path: '/' + menu.href,
        meta: {
          title: menu.name,
          icon: menu.icon,
          alwaysShow: true
        },
        component: Layout,
        children: menu.children.map((menu2: any) => {
          return {
            path: menu2.href,
            name: menu2.component || '',
            meta: { title: menu2.name, icon: menu2.icon },
            component: (resolve: any) =>
              require([`@/views/${menu2.component}/index.vue`], resolve)
          }
        })
      }
      accessedRoutes.push(route)
    })
    accessedRoutes.push({
      path: '*',
      component: () => import('@/views/error-page/404.vue'),
      meta: {
        hidden: true
      }
    })
    this.SET_ROUTES([])
  }
}

export const PermissionModule = getModule(Permission)
